package com.boot.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Set;

public class NioServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        Selector selector = Selector.open();
        serverChannel.socket().bind(new InetSocketAddress(6666));
        serverChannel.configureBlocking(false);//设置非阻塞
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true){

            if(selector.select(3000) == 0){//等待3秒 如果无事件发生就返回
                System.out.println("无事件，继续监听");
                continue;
            }
            //有事件发生
            Set<SelectionKey> selectionKeys = selector.selectedKeys();//获取selector上有事件的通道集合
            for (SelectionKey key: selectionKeys){

                if(key.isAcceptable()){//连接事件
                    SocketChannel socketChannel = serverChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("接受连接："+socketChannel.hashCode());
                }

                if(key.isReadable()){
                    //获取客户端channel
                    SocketChannel channel = (SocketChannel)key.channel();
                    ByteBuffer buffer = (ByteBuffer)key.attachment();
                    channel.read(buffer);
                    System.out.println("接受请求："+ new String(buffer.array()));
                }

                selectionKeys.remove(key);
            }

        }

    }
}
